package com.ocm.core.service.jackrabbit;

import java.util.HashMap;
import java.util.Map;

import javax.jcr.Node;
import javax.jcr.Session;

import com.ocm.core.context.ApplicationContextProvider;
import com.ocm.core.domain.PropertyType;
import com.ocm.core.exception.OCMException;
import com.ocm.core.service.JCRSecurityService;
import com.ocm.core.service.JCRService;

public class JCRSecurityServiceImpl implements JCRSecurityService {

   private static final String SYSPRO_SECURITYVALUE = "syspro_securityValue";

   private JCRService jcrService;

   public void processSecurity(Node instanceClass, String propertyName, String securityObj, boolean hasVersion) throws OCMException {
      try{
         Session session = instanceClass.getSession();
         Node referenceNode = null;
         if (instanceClass.hasProperty(propertyName)) {
            referenceNode = instanceClass.getProperty(propertyName).getNode();
         }
         if (referenceNode == null){
            Map<String, Object> properties = new HashMap<String, Object>();
            properties.put(SYSPRO_SECURITYVALUE, PropertyType.STRING.convertValue(securityObj));
            if (hasVersion){
               boolean hasCheckedOut = instanceClass.isCheckedOut();
               if (hasCheckedOut == false)
                  getJCRService().checkout(session, instanceClass.getIdentifier());

               referenceNode = getJCRService().addNode(session, instanceClass.getIdentifier(), propertyName, properties);
               instanceClass.setProperty(propertyName, referenceNode);
               getJCRService().checkin(session, instanceClass.getIdentifier(), null);

               if (hasCheckedOut == true)
                  getJCRService().checkout(session, instanceClass.getIdentifier());
            }else
               instanceClass.setProperty(propertyName, referenceNode);
         }else{
            referenceNode.setProperty(SYSPRO_SECURITYVALUE, securityObj);
         }
      }catch (Exception exception){
         throw new OCMException(exception);
      }
   }

   public String getSecurity(Node instanceClass, String propertyName) throws OCMException {
      try{
         Node referenceNode = null;
         if (instanceClass.hasProperty(propertyName)) {
            referenceNode = instanceClass.getProperty(propertyName).getNode();
         }
         String securityValue = null;
         if (referenceNode != null){
            securityValue = referenceNode.getProperty(SYSPRO_SECURITYVALUE).getString();
         }
         return securityValue;
      }catch (Exception exception){
         throw new OCMException(exception);
      }
   }

   public JCRService getJCRService() {
      if (jcrService == null)
         jcrService = (JCRService) ApplicationContextProvider.getApplicationContext().getBean("jcrService");
      return jcrService;
   }
}
